package com.yzl.frelink.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yzl.frelink.entities.dep.Deedge;
import com.yzl.frelink.entities.dep.Demap;
import com.yzl.frelink.entities.model.Model;
import com.yzl.frelink.service.CompilerService;
import com.yzl.frelink.service.matlab.DotCompiler;
import com.yzl.frelink.service.matlab.MatlabCompiler;

@Service
public class CompilerServiceImpl implements CompilerService {
    @Autowired
    MatlabCompiler matlabCompiler;

    @Override
    public void visualizeDependency(Demap demap, String outputPath) {
        StringBuilder reqtxt = new StringBuilder();
        StringBuilder vartxt = new StringBuilder();
        StringBuilder deptxt = new StringBuilder();

        Iterator<String> reqit = demap.getReqs().iterator();
        while (reqit.hasNext()) {
            String dereq = reqit.next();
            reqtxt.append("component \"").append(dereq).append("\"\n");
        }
        Iterator<String> varit = demap.getVars().iterator();
        while (varit.hasNext()) {
            String devar = varit.next();
            vartxt.append("node \"").append(devar).append("\" #Pink\n");
        };
        Iterator<Deedge> deit = demap.getEdges().iterator();
        while (deit.hasNext()) {
            Deedge deedge = deit.next();
            deptxt.append("\"").append(deedge.getSource()).append("\" --> \"").append(deedge.getTarget()).append("\"\n");
        }
        

        String resFile = "@startuml\n" + reqtxt.toString() + vartxt.toString() + deptxt.toString() + "@enduml";
        try {
            File dotFile = new File(outputPath);
            Writer writer = new OutputStreamWriter(new FileOutputStream(dotFile), "UTF-8");
            writer.write(resFile);
            writer.close();
        } catch (Exception e) {
            System.out.println("Error writing file: " + e.getMessage());
        }
    }

    @Override
    public void compileMatlabWithPosition(Model model) {
        DotCompiler.printModelDot(model);
        DotCompiler.setModelPosition(model);
        matlabCompiler.compileToMatlab(model);
    }
}
